﻿using UnityEngine;
using System.Collections;

public class PlayerAction : MonoBehaviour
{
	public enum PlayerType
	{
		Player,
		NPC,
	}
	
	public PlayerType playerType = PlayerType.Player;
	public float speed = 9.0f;
	public Vector3 targetPoint;
	public GameObject animationLayer;
	
	//If NPC
	public float reapeatRate = 5.0f;
	public float radiusOfWalking = 0.1f;
	private float randomAreaRate = 0.1f;
	
	public bool IsRunning {
		get{ return isRunning;}
	}
	
	public bool IsIdling {
		get{ return isIdling;}
	}
	
	//TODO 也许要删掉
	InputInfo _inputInfo;
	ClipAnimation _animation;
	//PlayerWalk playerWalk;
	Transform _trans;
	bool isRunning = false;
	bool isIdling = false;
	bool isborder;
	SmoothFollow follow;
	bool startWalkAround;
	Vector3 originalPosition;
	float originalSpeed;
	Vector3 direction;
	MouseReplace gameMouse;
	Transform clipAniTrans;
	Vector3 preFramePosition;
	
	void Awake ()
	{
		if (playerType == PlayerType.Player) {
			ModelLocator.getInstance ().addEventListener (ClientToClientFlag.CLIENT_CLICK_SCENE_OBJ, GetListenner);
		}
		
		_trans = transform;
	}
	
	private void GetListenner (object o, DispatchEventArgs e)
	{
		GameObject obj = e.data [0] as GameObject;
		switch (obj.name) {
		case "Door":
		case "NPC":
			{
				float randomRadiusX = Random.Range (-1f, 1f) * randomAreaRate;
				float randomRadiusY = Random.Range (-1f, 1f) * randomAreaRate;
				targetPoint = obj.transform.position;
				targetPoint.x += randomRadiusX;
				//targetPoint.y += randomRadiusY;
				_inputInfo.firstTouch = true;
				_inputInfo.hasSingleTouch = false;
				isIdling = false;
				isRunning = false;
				gameMouse.setMousePos (targetPoint);
				break;
			}
		}
	}
	
	void OnDestroy ()
	{
		ModelLocator.getInstance ().removeEventListener (ClientToClientFlag.CLIENT_CLICK_SCENE_OBJ, GetListenner);
	}
	
	public void npcautoMove (Vector3 position)
	{
		targetPoint = position;
		direction = targetPoint - _trans.position;
		_inputInfo.firstTouch = true;
		_inputInfo.hasSingleTouch = false;
		isIdling = false;
		isRunning = false;
	}
	
	// Use this for initialization
	void Start ()
	{
		_inputInfo = Camera.main.GetComponent<InputInfo> ();
		
		gameMouse = Camera.mainCamera.GetComponent<MouseReplace> ();
		
		//playerWalk = GetComponent<PlayerWalk> ();
		_animation = animationLayer.GetComponent<ClipAnimation> ();
		follow = Camera.main.GetComponent<SmoothFollow> ();
		clipAniTrans = _animation.transform;
		
		//playerWalk.onArriveDestination = Stop;
		
		if (playerType == PlayerType.NPC) {
			InvokeRepeating ("WalkAround", 0, reapeatRate);
		}
		
		originalPosition = _trans.position;
		targetPoint = originalPosition;
		originalSpeed = speed;
		
		Stop ();
	}
	
	// Update is called once per frame
	void LateUpdate ()
	{
		if (playerType != PlayerType.NPC) {
			if (!_inputInfo.firstTouch)
				return;

			if (_inputInfo.hasSingleTouch) {
				
				Vector3 mousePosition = _inputInfo.Hit.point;
				mousePosition.z = preFramePosition.z;
				direction = _inputInfo.Hit.point - _trans.position;
				if (Vector3.Distance (preFramePosition, mousePosition) < 0.06f) {
					return;
				}
				targetPoint = _inputInfo.Hit.point;
				isRunning = false;
				isIdling = false;
			}

			if (_inputInfo.hasLongTouch) {
				_inputInfo.mouseClick ();
				
				Vector3 mousePosition = _inputInfo.Hit.point;
				mousePosition.z = preFramePosition.z;
				direction = _inputInfo.Hit.point - _trans.position;
				if (Vector3.Distance (preFramePosition, mousePosition) < 0.06f) {
					return;
				}
				
				targetPoint = _inputInfo.Hit.point;
				//direction = targetPoint - _trans.position;
				_inputInfo.firstTouch = true;
				_inputInfo.hasSingleTouch = false;
				isIdling = false;
				isRunning = false;
				gameMouse.setMousePos (targetPoint);
			}
			
			direction = targetPoint - _trans.position;
			isborder = follow.IsBorder;
		} else {
			if (startWalkAround) {
				float randomRadiusX = Random.Range (-1f, 1f) * radiusOfWalking;
				float randomRadiusY = Random.Range (-1f, 1f) * radiusOfWalking;
				targetPoint = originalPosition;
				targetPoint.x += randomRadiusX;
				targetPoint.y += randomRadiusY;
				isborder = true;
				
				isRunning = false;
				isIdling = false;
				
				//playerWalk.direction = targetPoint - _trans.position;
				direction = targetPoint - _trans.position;
			} else {
				//isRunning = true;
			}
		}
		
		
		//playerWalk.speed = speed;
		
		if (isIdling)
			return;
		
		Run ();
		
		MoveTowards (targetPoint, isborder);
		
		preFramePosition = _trans.position;
	}
	
	void Stop ()
	{	
		if (isIdling)
			return;
		
		_animation.Play ("idle");
		isIdling = true;
		startWalkAround = false;
	}
	
	void Run ()
	{
		if (_animation.currentClip == GameDefine.ANISTR_RUN)
			return;
		
		_animation.Play ("run");
		isRunning = true;
		startWalkAround = false;
	}
	
	void WalkAround ()
	{
		startWalkAround = true;
	}

	public void StartWalkAround ()
	{
		if (!IsInvoking ("WalkAround")) {
			InvokeRepeating ("WalkAround", 0, reapeatRate);
		}
	}

	public void StopWalkAround ()
	{
		startWalkAround = false;
		if (IsInvoking ("WalkAround"))
			CancelInvoke ("WalkAround");
	}

	public void MoveTowards (Vector3 destination)
	{
		MoveTowards (destination, false);
	}

	public void MoveTowards (Vector3 destination, bool isBorder)
	{
		destination.z = _trans.position.z;
		
		Vector3 tempDestination = destination;
		
		if (!isBorder) {
			tempDestination.x = _trans.position.x;
		}

       
		
		//target = tempDestination;
		//tr = _trans.position;
		//de = destination;
		
		if (!follow.cameraIsMoving && follow.IsBorder == false) {
			_trans.position = Vector3.MoveTowards (_trans.position, destination, originalSpeed * Time.deltaTime);
		} else if (!float.IsNaN (speed * Time.deltaTime)) {
			_trans.position = Vector3.MoveTowards (_trans.position, tempDestination, speed * Time.deltaTime);
		}

		
		if (Vector3.Distance (_trans.position, destination) - 0.03f < 0) {
			if (follow.cameraIsMoving)
				return;
			
			if (_inputInfo.isHitNpc && playerType == PlayerType.Player) {
				ModelLocator.getInstance ().dispacthEvent (ClientToClientFlag.CLIENT_CLICK_NPC, 
				new object[] {UIManagement.Instance().OpenWindow(UIManagement.Instance().shallOpenWindowName,GameDefine.INVISIABLE)});
			}
			
			//TO modify
			if (GameDefine.Click_Task_One) {
				ModelLocator.getInstance ().dispacthEvent (ClientToClientFlag.CLIENT_CLICK_NPC, 
				new object[] { UIManagement.Instance().OpenWindow(UIManagement.Instance().shallOpenWindowName,GameDefine.INVISIABLE)});

				GameDefine.Click_Task_One = false;
			}
			
			_trans.position = destination;
			
			Stop ();
			return;
		}
		
		if (direction.x > 0) {
			clipAniTrans.localEulerAngles = Vector3.zero;	
		} else {
			clipAniTrans.localEulerAngles = new Vector3 (0, 180, 0);
		}
		
	}

	void OnClick ()
	{
		//°ŽÀàÐÍ£¬ŽŠÀí»Øµ÷£šÀàÐÍ·ÅÈ«ŸÖ£©
		switch (playerType) {
		/*
            case PlayerType.NPC:
                {
                    ModelLocator.getInstance().dispacthEvent(ClientToClientFlag.CLIENT_CLICK_NPC, new object[] { gameObject });//NPCÐèµÈŽý»Øµ÷
                    break;
                }
                */
		case PlayerType.Player:
			{
				ModelLocator.getInstance ().dispacthEvent (ClientToClientFlag.CLIENT_CLICK_PLAYER, new object[] { gameObject });//ÍæŒÒÖ±œÓÅÉ·¢ºóŽŠÀí
				break;
			}
		}
	}
	
	
}
